package org.dromara.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.exception.base.BaseException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.RandomUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.system.domain.AppMessageRemind;
import org.dromara.system.domain.AppWarehouse;
import org.dromara.system.mapper.AppMessageRemindMapper;
import org.dromara.system.mapper.AppWarehouseMapper;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.AppWarehouseOutBo;
import org.dromara.system.domain.vo.AppWarehouseOutVo;
import org.dromara.system.domain.AppWarehouseOut;
import org.dromara.system.mapper.AppWarehouseOutMapper;
import org.dromara.system.service.IAppWarehouseOutService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 出库单Service业务层处理
 *
 * @author Lion Li
 * @date 2025-10-29
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class AppWarehouseOutServiceImpl implements IAppWarehouseOutService {

    private final AppWarehouseOutMapper baseMapper;
    private final AppMessageRemindMapper appMessageRemindMapper;
    private final AppWarehouseMapper appWarehouseMapper;

    /**
     * 查询出库单
     *
     * @param id 主键
     * @return 出库单
     */
    @Override
    public AppWarehouseOutVo queryById(String id){
        LambdaQueryWrapper<AppWarehouseOut> appWarehouseOutLambdaQueryWrapper = new LambdaQueryWrapper<>();
        appWarehouseOutLambdaQueryWrapper.eq(AppWarehouseOut::getOutOrderNo, id);
        AppWarehouseOut appWarehouseOut = baseMapper.selectOne(appWarehouseOutLambdaQueryWrapper);
        if (appWarehouseOut.getTransportStatus()==2){
            appWarehouseOut.setWarehouseOutFlag(1);
        }else {
            appWarehouseOut.setWarehouseOutFlag(0);
        }
        return BeanUtil.toBean(appWarehouseOut, AppWarehouseOutVo.class);
    }

    /**
     * 分页查询出库单列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 出库单分页列表
     */
    @Override
    public TableDataInfo<AppWarehouseOutVo> queryPageList(AppWarehouseOutBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AppWarehouseOut> lqw = buildQueryWrapper(bo);
        if (bo.getType()==0){
            lqw.isNull(AppWarehouseOut::getArrivalImage);
        }
        if (bo.getType()==1){
            lqw.isNotNull(AppWarehouseOut::getArrivalImage);
        }
        if (bo.getType()==2){
            lqw.eq(AppWarehouseOut::getSalesReturn,1);
        }
        Page<AppWarehouseOutVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的出库单列表
     *
     * @param bo 查询条件
     * @return 出库单列表
     */
    @Override
    public List<AppWarehouseOutVo> queryList(AppWarehouseOutBo bo) {
        LambdaQueryWrapper<AppWarehouseOut> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<AppWarehouseOut> buildQueryWrapper(AppWarehouseOutBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AppWarehouseOut> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(AppWarehouseOut::getId);
        lqw.eq(StringUtils.isNotBlank(bo.getOutOrderNo()), AppWarehouseOut::getOutOrderNo, bo.getOutOrderNo());
        lqw.like(StringUtils.isNotBlank(bo.getCompanyName()), AppWarehouseOut::getCompanyName, bo.getCompanyName());
        lqw.like(StringUtils.isNotBlank(bo.getWarehouseName()), AppWarehouseOut::getWarehouseName, bo.getWarehouseName());
        lqw.eq(StringUtils.isNotBlank(bo.getGoodsType()), AppWarehouseOut::getGoodsType, bo.getGoodsType());
        lqw.eq(bo.getGoodsWeight() != null, AppWarehouseOut::getGoodsWeight, bo.getGoodsWeight());
        lqw.like(StringUtils.isNotBlank(bo.getCarrierName()), AppWarehouseOut::getCarrierName, bo.getCarrierName());
        lqw.eq(StringUtils.isNotBlank(bo.getCarrierContact()), AppWarehouseOut::getCarrierContact, bo.getCarrierContact());
        lqw.eq(StringUtils.isNotBlank(bo.getCarrierPlateNo()), AppWarehouseOut::getCarrierPlateNo, bo.getCarrierPlateNo());
        lqw.eq(StringUtils.isNotBlank(bo.getCarrierVehicle()), AppWarehouseOut::getCarrierVehicle, bo.getCarrierVehicle());
        lqw.eq(bo.getCarrierCost() != null, AppWarehouseOut::getCarrierCost, bo.getCarrierCost());
        lqw.eq(bo.getTransportStatus() != null, AppWarehouseOut::getTransportStatus, bo.getTransportStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getShipper()), AppWarehouseOut::getShipper, bo.getShipper());
        lqw.eq(bo.getShipDate() != null, AppWarehouseOut::getShipDate, bo.getShipDate());
        return lqw;
    }

    /**
     * 新增出库单
     *
     * @param bo 出库单
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(AppWarehouseOutBo bo) {
        AppWarehouseOut add = MapstructUtils.convert(bo, AppWarehouseOut.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改出库单
     *
     * @param bo 出库单
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(AppWarehouseOutBo bo) {
        AppWarehouseOut update = MapstructUtils.convert(bo, AppWarehouseOut.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AppWarehouseOut entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除出库单信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public R<Void> uploadReceivedOrder(AppWarehouseOutBo bo) {
        LambdaQueryWrapper<AppWarehouseOut> appWarehouseOutLambdaQueryWrapper = new LambdaQueryWrapper<>();
        appWarehouseOutLambdaQueryWrapper.eq(AppWarehouseOut::getOutOrderNo,bo.getOutOrderNo());
        AppWarehouseOut appWarehouseOut = baseMapper.selectOne(appWarehouseOutLambdaQueryWrapper);
        if (appWarehouseOut==null) {
            throw new BaseException("该出库单不存在");
        }
        appWarehouseOut.setArrivalImage(bo.getArrivalImage());
        appWarehouseOut.setArrivalDate(DateUtil.parse(bo.getArrivalDate()));
        appWarehouseOut.setTransportStatus(2L);
        baseMapper.updateById(appWarehouseOut);
        //推送消息给财务 待结算！
        AppMessageRemind appMessageRemind = new AppMessageRemind();
        appMessageRemind.setPlanCode(appWarehouseOut.getOutOrderNo());
        appMessageRemind.setRoleId(7);
        appMessageRemind.setRemark("待结算！");
        appMessageRemindMapper.insert(appMessageRemind);

        return R.ok();
    }

    @Override
    public R<?> saleReturn(String outOrderNo) {
        //退货
        LambdaQueryWrapper<AppWarehouseOut> appWarehouseOutLambdaQueryWrapper = new LambdaQueryWrapper<>();
        appWarehouseOutLambdaQueryWrapper.eq(AppWarehouseOut::getOutOrderNo,outOrderNo);
        AppWarehouseOut appWarehouseOut = baseMapper.selectOne(appWarehouseOutLambdaQueryWrapper);
        if (appWarehouseOut!=null){
            appWarehouseOut.setSalesReturn(1);
            baseMapper.updateById(appWarehouseOut);
            //退货之后 货物返回
            LambdaQueryWrapper<AppWarehouse> appWarehouseLambdaQueryWrapper = new LambdaQueryWrapper<>();
            appWarehouseLambdaQueryWrapper.eq(AppWarehouse::getId,appWarehouseOut.getWarehouseId());
            appWarehouseLambdaQueryWrapper.eq(AppWarehouse::getGoodsType,appWarehouseOut.getGoodsType());
            AppWarehouse appWarehouse = appWarehouseMapper.selectOne(appWarehouseLambdaQueryWrapper);
            if (appWarehouse!=null){
                appWarehouse.setStock(appWarehouse.getStock()+appWarehouseOut.getGoodsWeight());
                appWarehouseMapper.updateById(appWarehouse);
            }
        }
        return R.ok();
    }
}
